<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <style>
      .upimgBtn {
        width: 120px;
        height: 40px;
        background-color: aquamarine;
        border-radius: 4px;
        box-shadow: 2px 2px 0 #ccc;
        text-align: center;
        line-height: 40px;
        color: chocolate;
        margin: 20px 0;
      }
      .content {
        width: 406px;
        height: 400px;
        margin: 0 auto;
        overflow: hidden;
      }
      .content textarea {
        width: 400px;
        height: 200px;
      }
      .content select {
        width: 120px;
        height: 30px;
        float: left;
      }
      .content .button {
        width: 100px;
        height: 30px;
        background-color: #ffcc00;
        border-radius: 4px;
        box-shadow: 2px 2px 0 #ccc;
        text-align: center;
        line-height: 30px;
        color: #000;
        float: left;
        margin-left: 10px;
      }
      .textContent {
        width: 400px;
        height: 400px;
        margin: 0 auto;
        overflow-y: scroll;
        background-color: #fafafa;
      }
    </style>
    <div id="el">
      <h1 style="text-align:center;">聊天室</h1>
      <div class="textContent">
        <p v-for="item in msgArr">
          <span style="color:blue">{{ item.name }}</span>
          <span v-if="item.msg">{{ item.msg }}</span>
          <img v-if="item.img" :src="item.img" alt="" style="max-width:300px" />
        </p>
      </div>
      <div v-if="!hasAddUser">
        <input type="text" v-model="userName" />
        <input type="password" v-model="password" />
        <button @click="addName">一键登录注册</button>
      </div>
      <div v-if="hasAddUser" class="content">
        <textarea v-model="msg"></textarea>
        <input
          ref="inputFile"
          type="file"
          class="form-control"
          @change="onFileChange"
          style="display:none"
        />
        <div @click="uploadImg" class="upimgBtn">上传图片</div>
        <select v-model="lan">
          <option :value="item.value" v-for="item in lans">{{
            item.name
          }}</option>
        </select>
        <div class="button" @click="sendMsg">发送消息</div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="./js/MD5.js"></script>
    <script>
      //   import axios from 'axios';
      //  import MD5 from './js/MD5.js';
      let socket = io.connect('http://www.arnno.com/news');
      var vue = new Vue({
        el: "#el",
        data() {
          return {
            msg: "",
            userName: "",
            password: "",
            hasAddUser: false,
            msgArr: [],
            image: "",
            lan: "",
            lans: [
              { value: "", name: "请选择语言" },
              { value: "zh", name: "中文" },
              { value: "en", name: "英文" },
              { value: "yue", name: "粤语" },
              { value: "wyw", name: "文言文" },
              { value: "jp", name: "日语" },
              { value: "kor", name: "韩语" },
              { value: "fra", name: "法语" },
              { value: "spa", name: "西班牙语" },
              { value: "th", name: "泰语" },
              { value: "ara", name: "阿拉伯语" },
              { value: "ru", name: "俄语" },
              { value: "pt", name: "葡萄牙语" },
              { value: "de", name: "德语" },
              { value: "it", name: "意大利语" },
              { value: "el", name: "希腊语" },
              { value: "nl", name: "荷兰语" },
              { value: "pl", name: "波兰语" },
              { value: "bul", name: "保加利亚语" },
              { value: "est", name: "爱沙尼亚语" },
              { value: "dan", name: "丹麦语" },
              { value: "fin", name: "芬兰语" },
              { value: "cs", name: "捷克语" },
              { value: "rom", name: "罗马尼亚语" },
              { value: "slo", name: "斯洛文尼亚语" },
              { value: "swe", name: "瑞典语" },
              { value: "hu", name: "匈牙利语" },
              { value: "cht", name: "繁体中文" },
              { value: "vie", name: "越南语" }
            ],
            result: ""
          };
        },
        created() {
          if (
            !localStorage.getItem("user_name") ||
            localStorage.getItem("user_name") == "undefined"
          ) {
            this.hasAddUser = false;
          } else {
            this.userName = localStorage.getItem("user_name");
            this.hasAddUser = true;
          }
        },
        mounted() {
          socket.on("new msg", data => {
            this.msgArr.push(data);
          });
          socket.on("new img", data => {
            this.msgArr.push(data);
          });
        },
        methods: {
          uploadImg() {
            console.log(this.$refs.inputFile)
            this.$refs.inputFile.click();
          },
          onFileChange(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;
            this.createImage(files[0]);
            this.$refs.inputFile.value = null;
          },
          async createImage(file) {
            var image = new Image();
            var reader = new FileReader();
            var vm = this;

            reader.onload = e => {
              vm.image = e.target.result;
              this.sendImg();
            };
            reader.readAsDataURL(file);
          },
          addName() {
            if (this.userName) {
              // this.hasAddUser = true;
              // localStorage.setItem("userName", this.userName);
              // socket.emit("add user", this.userName);
              axios
                .post("/v1/loginOrRegister", {
                  name: this.userName,
                  password: MD5(this.password)
                })
                .then(res => {
                  if (res.data.errorCode == 0) {
                    localStorage.setItem("user_name", res.data.data.user_name);
                    localStorage.setItem("user_dir", res.data.data.user_dir);
                    localStorage.setItem(
                      "user_token",
                      res.data.data.user_token
                    );
                    this.hasAddUser = true;
                  } else {
                    alert("少来，一看你就不是好人！");
                  }
                });
            }
          },
          sendImg() {
            this.msgArr.push({
              name: this.userName + ":",
              img: this.image
            });
            socket.emit("send img", {
              name: this.userName + ":",
              img: this.image,
              dir: localStorage.getItem("user_dir")
            });
          },
          async sendMsg() {
            if (!this.msg) {
              return;
            }
            let res = "";
            if (this.lan) {
              res = await this.trans();
            }
            if (res && res.status == 200)
              this.result = res.data.trans_result[0].dst;
            this.msgArr.push({
              name: this.userName + ":",
              msg: this.result ? this.result : this.msg
            });
            socket.emit("send msg", {
              name: this.userName + ":",
              msg: this.result ? this.result : this.msg
            });
            this.result = "";
            this.msg = "";
          },
          trans() {
            if (!this.lan || !this.msg) return;
            return axios.post("/v1/trans", {
              lan: this.lan,
              tranContent: this.msg
            });
          }
        }
      });
    </script>
  </body>
</html>
